<?php

declare (strict_types=1);

namespace magein\pay;

use magein\utils\Result;

class PayException extends \Exception
{
    public function __construct($message = '', $code = 0, \Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }

    /**
     * @param $code
     * @param $data
     * @throws PayException
     */
    public static function code($code, $data = null)
    {
        $messages = PayConfig::codes();

        self::json($messages[$code] ?? '支付发生错误', $code, $data);
    }

    /**
     * @param $message
     * @param int|string $code
     * @param $data
     * @throws PayException
     */
    public static function json($message, $code = 1, $data = null)
    {
        $message = json_encode([
            'code' => $code,
            'msg' => $message,
            'data' => $data,
        ], JSON_UNESCAPED_UNICODE);

        throw new self($message, 200);
    }

    public function toArray()
    {
        if ($this->getMessage()) {
            return json_decode($this->getMessage(), true);
        }

        return [];
    }

    public function toResult(): Result
    {
        $data = $this->toArray();

        if ($data) {
            return Result::error($data['msg'] ?? '', intval($data['code'] ?? 0) ?: 1, $data['data']);
        }

        return Result::error();
    }
}